<?php
namespace Home\Model;
use Home\Common\BaseModel;
use \Think\Db;


class GoodsModel extends BaseModel  {
    // 默认 会员ID
    //public $member_id = 714;

    /**
     * @param $pid
     * @param $sid
     * 商品详细
     */
    public function getbydetail($id){

        //货品详情页面
        $product = M('b2c_store_product sp')
            ->join("LEFT JOIN {$this->pre}b2c_products p ON p.product_id = sp.product_id")
            ->join("LEFT JOIN {$this->pre}b2c_goods g ON g.goods_id = p.goods_id")
            ->where(" sp.store_pid = $id")
            ->field("p.`name`,p.spec_info,sp.price,g.highlight,g.intro,p.product_id,g.goods_id,sp.marketprice,sp.local_id,sp.store,sp.discount,sp.store_pid,sp.sales_num,sp.explain,g.goods_property")
            ->find();
        ($product['discount']!=0)?$product['price']=$product['discount']:$product['price']=$product['price'];
         $product['highlight'] = explode(";", $product['highlight']);
        $product['goods_property'] = $product['goods_property'] ? json_decode($product['goods_property'], true): '';
        return $product;

    }

    /**
     *用户购物车数量
     */
    public function getcartnum(){
        //查询该用户购物车总数量
        $car_num = M('b2c_carts')->where('member_id='.session('userInfo')['member_id'])->field('SUM(cart_num) as num')->find();
        if(empty($car_num['num'])){
            $car_num['num'] = 0;
        }
        return $car_num;

    }
    /**
     * 店铺商品相关 规格货品
     */
    public function getproduct($id){

        $gid = M('b2c_store_product')->where(['store_pid'=>$id])->field('goods_id,local_id')->find();


        //同商品货品不一致的 货品列表  上架
        $product_list = M('b2c_store_product sp')
            ->join("left join {$this->pre}b2c_products p  ON sp.goods_id = p.goods_id and sp.product_id = p.product_id")
            ->where(['sp.goods_id'=>$gid['goods_id'],'sp.store_status'=>'true','sp.local_id'=>$gid['local_id']])
            ->field("sp.price,sp.store,sp.store_pid,sp.freez,p.spec_info,sp.marketprice,sp.product_id,sp.local_id")
            ->select();


        //所有规格商品库存都为 0

        /*$store = M('b2c_store_product sp')
            ->join("left join {$this->pre}b2c_products p  ON sp.product_id = p.product_id")
            ->where(" sp.store_pid = $id  and  sp.store_status = 'true' and sp.store > sp.freez" )
            ->field("sp.price,sp.store,p.spec_info,sp.marketprice,sp.product_id")
            ->select();

        if(empty($store)){
            $Pnum = 0;
        }else{
            $Pnum = count($store);
        }*/

        //判断闪购
        $n_num = 0;
        foreach ($product_list as $k=>$item){
            // $product_list[$k]['num'] = $Pnum;
            if($product_list[$k]['spec_info']!=''){
                $n_num ++;
                $product_list['spec_num'] = 1;
                $product_list['spec_num_total'] = $n_num;
            }else{
                $product_list['spec_num'] = 0;
            }
            //判断货品是否是闪购
            $flashGoods = $this->checkGoodsIsStarBuy($item['store_pid']);
            if(!empty($flashGoods)){
                $product_list[$k]['price'] = $flashGoods['promotion_price'];
                if($flashGoods['initnum']>0){
                    $product_list[$k]['enStore'] = 1;
                }elseif($flashGoods['initnum']==0){
                    $product_list[$k]['enStore'] = 0;
                }
                $product_list[$k]['msg'] = '闪';
            }else{
                //判断是否是促销商品
                $proGood = $this->checkGoodsIsPromotion($gid['local_id'], $item['store_pid']);
                if (!empty($proGood) and $product_list[$k]['price'] != $proGood['price']){
                    $product_list[$k]['price'] = $proGood['price'];
                    $product_list[$k]['msg'] = '促销';
                }

                //判断库存是否足够
                if($item['store'] >  $item['freez']){
                    $product_list[$k]['enStore'] = 1;
                }else{
                    $product_list[$k]['enStore'] = 0;
                }
            }
            // 查询购物车该商品数量
            $where = [
                'member_id'=>session('userInfo')['member_id'],
                 'local_id' =>$item['local_id'],
                 'product_id' => $item['product_id']

            ];
            $gDetail_Cart_num = M('b2c_carts')->where($where)->getField('cart_num') ?: 0;

            $product_list[$k]['gDetail_Cart_num'] = $gDetail_Cart_num;

        }
        //print_r($product_list);
        return $product_list;

    }

    /**获取商品的相册
     * @param $goods_id
     */
    public function getGoodsPhotos($goods_id) {
        $fields = 'l_ident,l_url';
        $where = ['target_id' => $goods_id, 'target_type' => 'goods'];
        $phones = M('image_image_attach')
            ->alias('a')
            ->join(C('DB_PREFIX').'image_image b on a.image_id=b.image_id')
            ->field($fields)
            ->where($where)
            ->select();
        if ($phones) {
            foreach ($phones as &$item) {

                if($item['l_url']=="/public/l_images"){
                    $item['l_url'] = '';
                }else{
                    $item['l_url'] = '/Uploads/'.$item['l_url'];
                }

            }
        }
        return $phones;
    }

    /**判断当前的货品是否是闪购产品 并返回闪购的时间和价格
     * @param $store_pid
     */
    public function checkGoodsIsStarBuy($store_pid) {
        $info = M('starbuy_flashsales_goods')
            ->alias('a')
            ->join(C('DB_PREFIX').'starbuy_flashsales_time b on a.tid=b.tid')
            ->join(C('DB_PREFIX').'starbuy_flashsales sf on sf.special_id=b.special_id')
            ->field('a.promotion_price,a.ini_y_tnum,a.initnum,a.repertory_num,a.countnum,a.store_pid,a.id,b.tid,b.limit,b.begin_time,b.end_time,sf.is_start')
            ->where(['a.store_pid'=>$store_pid])
            ->select();
        $time = time();
        foreach($info as $k1 => &$v1){
            //销毁过期的和未开始的
            if($time < $v1['begin_time'] || $time >= $v1['end_time'] || $v1['is_start']=='0'){
                unset($info[$k1]);
            }
        }
        sort($info);
        return $info ? $info[0]: [];
    }

    /**
     * 商品促销价格
     * @param $local_id
     * @param $store_id
     * @return int|mixed
     */
    public function checkGoodsIsPromotion($local_id, $store_id){
        $time = time();
        $lists = M('b2c_store_goods_promotion')
            ->where('local_id = %d and display = 1 and (start_time < %d and end_time > %d)', [$local_id, $time, $time])
            ->field(['store_promotion'])->select();
        $proPrice = [];
        foreach ($lists as $list){
            $proStoreStr = $list['store_promotion'];
            if (empty($proStoreStr)) continue;
            $storeIds = json_decode($proStoreStr, true);
            if (!is_array($storeIds)) continue;
            if (array_key_exists($store_id, $storeIds)){
                $proPrice['price'] = $storeIds[$store_id];
                break;
            }
        }
        return $proPrice;
    }

    /**获取货品的评论
     * @param $store_pid
     */
    public function getStoreProductComments($store_pid, $p=1, $page=5) {
        //汇总信息:综合评分5.0 好评率98% 128条评价
        static $info;
        if (empty($info)) {
            $fields = 'grade, good_comment, comment_num, good_num';
            $info = M('b2c_store_product')
                ->cache(true, 3600, 'redis')
                ->where(['store_pid'=>$store_pid])
                ->field($fields)
                ->find();
        }

        //评论列表
        //todo 微信用户的名称和头像
        $count = M('b2c_goods_comment')
            ->alias('a')
            ->join(C('DB_PREFIX').'b2c_members b on a.member_id=b.member_id', 'LEFT')
            ->join(C('DB_PREFIX').'b2c_temp_user c on b.openid=c.openid')
            ->cache(true, 3600, 'redis')
            ->where(['a.store_pid'=>$store_pid])
            ->count();
        $list =[];
        $maxpage = 1;
        if ($count) {
            $maxpage = ceil($count / $page);
            $fields = 'point_id, product_point, logistics_point, type_id, a.member_id, a.local_id, store_pid, content, FROM_UNIXTIME(`create_time`,"%Y-%m-%d %H:%i:%s" ) AS create_time, b.name,b.nickname, c.logo';
            $list = M('b2c_goods_comment')
                ->alias('a')
                ->join(C('DB_PREFIX').'b2c_members b on a.member_id=b.member_id', 'LEFT')
                ->join(C('DB_PREFIX').'b2c_temp_user c on b.openid=c.openid')
                ->cache(true, 3600, 'redis')
                ->where(['a.store_pid'=>$store_pid])
                ->field($fields)
                ->order('point_id desc')
                ->page($p, $page)
                ->select();

        }
        return ['info'=>$info, 'list'=>$list, 'totalnum'=>$count, 'p'=>$p, 'page'=>$page, 'maxpage'=>$maxpage];
    }

    /**
     * 查询当前货品在购物车中的个数
     */
    public function getDetailNumInCart($local_id, $product_id) {
        $where = [
            'member_id'=>session('userInfo')['member_id'],
            'local_id' => $local_id,
            'product_id' => $product_id
        ];
        return M('b2c_carts')->where($where)->getField('cart_num') ?: 0;
    }

    /**获取商品的标签
     * @param $local_id
     * @param $product_id
     * @return array
     */
    public function getProductTags($local_id, $product_id) {
        $list = M('store_products_label_relation')
            ->alias('a')
            ->join(C('DB_PREFIX').'store_products_label b on a.label_id = b.label_id', 'left')
            ->where(['a.product_id' => $product_id, 'a.local_id' => $local_id])
            ->field(['b.label_name'])
            ->select();
        return $list ? array_column($list, 'label_name') : [];
    }
}